package client.components;

import java.util.Map;

import client.bean.Member;
import client.bean.Plan;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.visualization.client.VisualizationUtils;

public class PlanView extends SimplePanel {
	private Plan plan;

	public PlanView(Plan plan) {
		this.plan = plan;

		repaint();
	}

	public void repaint() {
		clear();
		Runnable onLoadCallback = new Runnable() {
			public void run() {

				final VerticalPanel pageLayout = new VerticalPanel();
				pageLayout.setWidth("100%");

				pageLayout.add(new HTML("<h1>" + plan.getName() + "</h1>"));
				pageLayout.add(new PlanTimeline(plan));
				fillLayoutWithMembersList(pageLayout);
				pageLayout.add(new HTML("<hr>"));
				pageLayout.add(createAddMemberButton());
				pageLayout.add(createInformMembersButton());
				add(pageLayout);
			}

			private void fillLayoutWithMembersList(final VerticalPanel pageLayout) {
				pageLayout.add(new HTML("<hr>"));
				pageLayout.add(new HTML("<b>Member list:<b/>"));

				final VerticalPanel membersList = new VerticalPanel();
				int index = 1;
				for (Map.Entry<Member, Boolean> memberEntry : plan.getMembers().entrySet()) {
					String accepted = memberEntry.getValue() ? "accepted" : "waiting";
					String text = index + ". " + memberEntry.getKey().getName() + ": " + accepted;
					pageLayout.add(new HTML(text));
					pageLayout.add(createEditButton(memberEntry.getKey()));
					index++;
				}

				pageLayout.add(membersList);
			}

			private Button createEditButton(final Member member) {
				Button button = new Button("Edit");
				button.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						final NewMemberDialogBox db = new NewMemberDialogBox(PlanView.this, plan, member);
						db.show();
					}
				});
				return button;
			}

			private Button createInformMembersButton() {
				Button inform = new Button("Inform members by email");
				inform.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						client.TimeBookController.informUsersByEmail(plan);
					}
				});
				return inform;
			}

			private Button createAddMemberButton() {
				Button addMember = new Button("Add member");
				addMember.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						final NewMemberDialogBox db = new NewMemberDialogBox(PlanView.this, plan, null);
						db.show();
					}
				});
				return addMember;
			}
		};

		VisualizationUtils.loadVisualizationApi(onLoadCallback);
	}
}
